package com.rcadmin.core.app.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rcadmin.common.prop.TemplateResProp;
import com.rcadmin.core.app.bean.UserInfo;
import com.rcadmin.core.app.session.SessionControl;
import com.rcadmin.core.app.session.SessionException;
import com.rcadmin.core.web.BaseAction;

@WebFilter(filterName = "LoginFilter", urlPatterns = { "*.op", "/templateres/*" }, initParams = {
		@WebInitParam(name = "toLogin", value = "toLogin.op"),
		@WebInitParam(name = "login", value = "login.op"),
		@WebInitParam(name = "logout", value = "logOut.op") })
public class LoginFilter implements Filter {
	private static Logger logger = LoggerFactory.getLogger(BaseAction.class);

	private String toLogin = "/toLogin.op";
	private List<String> ignoreUrl;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResposne, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResposne;
		String contextPath = request.getContextPath();
		String loginPage = contextPath + "/" + toLogin;
		String reqUrl = request.getRequestURL().toString();

		if (!isIgnoreUrl(reqUrl) || StringUtils.isEmpty(reqUrl)) {
			UserInfo userInfo = null;
			try {
				userInfo = SessionControl.getUserInfo(request);
			} catch (SessionException e) {
				// logger.error("fail to get user session!", e);
			}

			if (userInfo == null) {
				response.sendRedirect(loginPage + "?outsession=0");
				return;
			}
		}
		if (reqUrl.contains(TemplateResProp.urlPrefix)
				&& request.getParameter("preview") == null
				&& reqUrl.contains(".html")) {

			if (reqUrl.indexOf("?") > -1)
				reqUrl += "&preview=true";
			else
				reqUrl += "?preview=true";
			reqUrl += "&" + request.getQueryString();
			response.sendRedirect(reqUrl);
			return;
		}
		filterChain.doFilter(request, response);
	}

	private boolean isIgnoreUrl(String reqUrl) {
		for (String url : ignoreUrl) {
			if (reqUrl.contains(url) || reqUrl.endsWith(url)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ignoreUrl = new ArrayList<String>();
		toLogin = filterConfig.getInitParameter("toLogin");
		Enumeration<String> paramNames = filterConfig.getInitParameterNames();
		String paramName;
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			ignoreUrl.add(filterConfig.getInitParameter(paramName));
		}
	}
}
